package com.zyf.controller;

import com.zyf.common.result.Result;
import com.zyf.service.PaymentInfoService;
import com.zyf.service.WXPayService;
import io.swagger.annotations.Api;
import io.swagger.annotations.ApiImplicitParam;
import io.swagger.annotations.ApiOperation;
import org.springframework.beans.factory.annotation.Autowired;
import org.springframework.web.bind.annotation.GetMapping;
import org.springframework.web.bind.annotation.PathVariable;
import org.springframework.web.bind.annotation.RequestMapping;
import org.springframework.web.bind.annotation.RestController;

import java.util.Map;

/** 微信支付 接口
 * @author zyf
 * @date 2021年06月02日 17:35
 */
@Api(value = "微信支付")
@RestController
@RequestMapping("/api/order/weixin")
public class WXPayController {

    @Autowired
    private WXPayService wxPayService;

    @Autowired
    private PaymentInfoService paymentInfoService;

    @ApiOperation(value = "生成微信支付二维码")
    @GetMapping("/createNative/{orderId}")
    @ApiImplicitParam(name = "orderId", value = "订单id" )
    public Result createNative(@PathVariable("orderId") String orderId){
        Map map = wxPayService.createNative(orderId);
        return Result.ok(map);
    }

    @ApiOperation(value = "查询支付订单状态")
    @GetMapping("/queryPayStatus/{orderId}")
    @ApiImplicitParam(name = "orderId",value = "订单id")
    public Result queryPayStatus(@PathVariable("orderId") String orderId){
        //调用微信接口实现支付状态查询
        Map<String,String> map = wxPayService.queryPayStatus(orderId);
        //支付判断
        if (map == null){
            return Result.fail().message("支付出错");
        }
        if ("SUCCESS".equals(map.get("trade_state"))){//支付成功
            //更新订单状态
            String outTradeNo = map.get("out_trade_no");
            paymentInfoService.paySuccess(outTradeNo,map);
            return Result.ok().message("支付成功");
        }
        return Result.ok().message("支付中");
    }


}
